package edu.swust.graduation_project.eauction.activity

import android.os.Bundle
import android.view.KeyEvent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.bottomnavigation.BottomNavigationView
import edu.swust.graduation_project.eauction.R
import edu.swust.graduation_project.eauction.fragment.AddItemFragment
import edu.swust.graduation_project.eauction.fragment.ItemFragment
import edu.swust.graduation_project.eauction.fragment.UserFragment
import kotlin.system.exitProcess


class ContainerActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_container)
        val mBnvContainer = findViewById<BottomNavigationView>(R.id.bn_main)
        val mAddItemFragment = AddItemFragment()
        val mItemFragment = ItemFragment()
        val mUserFragment = UserFragment()
        mBnvContainer.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_item -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fl_container, mItemFragment).commitAllowingStateLoss()
                }

                R.id.navigation_additem -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fl_container, mAddItemFragment).commitAllowingStateLoss()
                }
                R.id.navigation_user -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fl_container, mUserFragment).commitAllowingStateLoss()
                }
            }
            true
        }
        supportFragmentManager.beginTransaction().add(R.id.fl_container, mItemFragment)
            .commitAllowingStateLoss()
    }
    //再次点击退出程序功能
    private var firstTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) { // 点击了返回按键
            exitApp()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exitApp() {
        if (System.currentTimeMillis() - firstTime >= 2000) {
            Toast.makeText(this,"再按一次退出程序",Toast.LENGTH_SHORT).show()
            firstTime = System.currentTimeMillis()
        } else {
            finish()
            exitProcess(0)
        }
    }
}